package routing;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1. 建立连接(Connection)
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置连接参数:ip,端口号,用户名,密码,虚拟机
        connectionFactory.setHost("116.205.165.92");//ip
        connectionFactory.setPort(5672);//端口号,默认是5672
        connectionFactory.setUsername("Test");//用户名
        connectionFactory.setPassword("123");//密码
        connectionFactory.setVirtualHost("TestVirtualHost");//设置操作的虚拟机
        Connection connection = connectionFactory.newConnection();//从连接工厂中获取到连接

        //2. 开启通道(Channel)
        Channel channel = connection.createChannel();//通过connection开启通道

        //3. 声明交换机

        channel.exchangeDeclare("DIRECT_EXCHANGE", BuiltinExchangeType.DIRECT, true);

        //4.声明队列
        /**
         * queueDeclare方法的参数
         * queue:队列名
         * durable:可持久化
         * exclusive:是否独占(是否只能由一个消费者进行消费)
         * autoDelete:当没有人消费时,是否自动删除
         * arguments:参数
         */
        channel.queueDeclare("DIRQueue1", true, false, false, null);
        channel.queueDeclare("DIRQueue2", true, false, false, null);

        //5.交换机和队列进行绑定
        /**
         * 参数1:queue,队列名
         * 参数2:exchange,交换机名
         * 参数3:routingkey:路由key
         * 如果交换机类型为fanout,routingkey设置为""表示每个消费者都可以接受到全部信息
         */
        channel.queueBind("DIRQueue1", "DIRECT_EXCHANGE", "a");
        channel.queueBind("DIRQueue2", "DIRECT_EXCHANGE", "a");
        channel.queueBind("DIRQueue2", "DIRECT_EXCHANGE", "b");
        channel.queueBind("DIRQueue2", "DIRECT_EXCHANGE", "c");


        String msgA = "HelloDirA";//消息的内容
        String msgB = "HelloDirB";//消息的内容
        String msgC = "HelloDirC";//消息的内容
        //发送消息
        /**
         * basicPublish方法的参数
         * exchange:交换机名称
         * routingKey:routingKey和队列名保持一致
         * props:属性配置
         * body:消息的内容
         */
        channel.basicPublish("DIRECT_EXCHANGE", "a", null, msgA.getBytes());
        channel.basicPublish("DIRECT_EXCHANGE", "b", null, msgB.getBytes());
        channel.basicPublish("DIRECT_EXCHANGE", "c", null, msgC.getBytes());

        System.out.println("消息发送成功");
        //6.释放资源
        channel.close();
        connection.close();

    }
}